package com.power.authservice.impl;

import com.power.authservice.factory.LoginStrategyFactory;
import com.power.authservice.strategy.LoginStrategy;
import com.power.constant.AuthConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 项目自己的认证流程
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    //获取登录策略 这个是策略的工厂，下面根据聚体登录类型去创建对应的登录类
    @Autowired
    private LoginStrategyFactory loginStrategyFactory;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //获取请求头中的登录类型
        String logintype = request.getHeader(AuthConstants.LOGIN_TYPE);
        if (!StringUtils.hasText(logintype))
        {
         throw  new InternalAuthenticationServiceException("登录类型不能为空");
        }
        String s = convertToBackendFormat(logintype);
        LoginStrategy instance = loginStrategyFactory.getInstance(s);
        if (instance==null)
        {
            throw new InternalAuthenticationServiceException("登录类型不存在,请联系管理员");
        }
        return instance.realLogin(username);
    }
    public String convertToBackendFormat(String frontendFormat) {
        // 假设前端传来的格式为驼峰命名，需要转换为下划线命名
        StringBuilder backendFormat = new StringBuilder();
        for (int i = 0; i < frontendFormat.length(); i++) {
            char c = frontendFormat.charAt(i);
            if (Character.isUpperCase(c)) {
                backendFormat.append('_').append(Character.toLowerCase(c));
            } else {
                backendFormat.append(c);
            }
        }
        return backendFormat.toString();
    }
}
